package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.api.vo.SkuLockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.ISkuStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.vo.SkuStockVo;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品sku库存表 服务实现类
 * </p>
 *
 * @author xiongkunYang
 * @since 2025/05/26 18:30
 */
@Service
@RequiredArgsConstructor
public class SkuStockServiceImpl extends ServiceImpl<SkuStockMapper, SkuStock> implements ISkuStockService {

    private final RedisTemplate<Object, Object> redisTemplate;

    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        // 根据skuId查询商品库存
        LambdaQueryWrapper<SkuStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(SkuStock::getSkuId, skuId);
        SkuStock skuStock = baseMapper.selectOne(queryWrapper);
        // 封装数据
        SkuStockVo skuStockVo = new SkuStockVo();
        skuStockVo.setAvailableNum(skuStock.getAvailableNum());
        skuStockVo.setSaleNum(skuStock.getSaleNum());
        skuStockVo.setSkuId(skuId);
        return skuStockVo;
    }

    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        // 遍历所有商品，验库存并锁库存
        skuLockVoList.forEach(skuLockVo -> {
            SkuStock skuStock = this.baseMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            skuLockVo.setHaveStock(skuStock != null);
        });

        // 只要有一个商品库存不足
        if (skuLockVoList.stream().anyMatch(skuLockVo -> !skuLockVo.isHaveStock())) {
            // 过滤出所有库存不足的商品
            List<SkuLockVo> noStockList = skuLockVoList.stream()
                    .filter(skuLockVo -> !skuLockVo.isHaveStock())
                    .toList();

            // 组装错误提示
            StringBuffer errorMsg = new StringBuffer();
            noStockList.forEach(skuLockVo -> errorMsg.append(skuLockVo.getSkuName())
                    .append("库存不足，剩余库存：")
                    .append(this.baseMapper.selectById(skuLockVo.getSkuId()).getAvailableNum())
                    .append("；"));
            //返回错误信息
            return errorMsg.toString();
        } else {
            //所有商品库存充足
            for (SkuLockVo skuLockVo : skuLockVoList) {
                //锁定库存
                this.baseMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            }
        }
        // 如果所有商品都锁定成功的情况下，需要缓存锁定信息到redis。以方便将来解锁库存 或者 减库存
        String dataKey = "sku:lock:data:" + orderNo;
        this.redisTemplate.opsForValue().set(dataKey, skuLockVoList);
        return "success";
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void unlock(String orderNo) {
        // 幂等性处理
        String key = "sku:unlock:" + orderNo;
        Boolean isFirst = this.redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.MINUTES);
        if (Boolean.FALSE.equals(isFirst)) {
            return;
        }

        // 获取锁定库存的缓存信息
        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>) this.redisTemplate.opsForValue().get(dataKey);
        if (!CollectionUtils.isEmpty(skuLockVoList)) {
            skuLockVoList.forEach(skuLockVo -> {
                // 解锁库存
                this.baseMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            });
        }

        // 解锁库存之后，删除锁定库存的缓存
        this.redisTemplate.delete(dataKey);


    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void minus(String orderNo) {

        // 幂等性处理
        String key = "sku:minus:" + orderNo;
        Boolean isFirst = this.redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.MINUTES);
        if (Boolean.FALSE.equals(isFirst)) {
            return;
        }

        // 获取锁定库存的缓存信息
        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuStock> skuStockList = (List<SkuStock>) this.redisTemplate.opsForValue().get(dataKey);
        if (!CollectionUtils.isEmpty(skuStockList)) {
            skuStockList.forEach(skuStock -> {
                // 减库存
                this.baseMapper.minus(skuStock.getSkuId(), skuStock.getSaleNum());
            });
        }

        //  减库存之后，删除锁定库存的缓存
        this.redisTemplate.delete(dataKey);
    }
}
